package vn.edu.ptithcm.pim.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.StringMultipartFileEditor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import vn.edu.ptithcm.pim.constant.Constants;
import vn.edu.ptithcm.pim.constant.UrlConstants;
import vn.edu.ptithcm.pim.dom.Employee;
import vn.edu.ptithcm.pim.dom.User;
import vn.edu.ptithcm.pim.service.DepartmentService;
import vn.edu.ptithcm.pim.service.DiplomaService;
import vn.edu.ptithcm.pim.service.EmployeeService;
import vn.edu.ptithcm.pim.service.RankService;
import vn.edu.ptithcm.pim.service.UniversityService;
import vn.edu.ptithcm.pim.service.UserService;
import vn.edu.ptithcm.pim.util.FileUtil;
import vn.edu.ptithcm.pim.util.ParamUtil;

@SuppressWarnings("deprecation")
public class HandleEmployeeController extends SimpleFormController {

	private EmployeeService employeeService;
	private UserService userService;
	private RankService rankService;
	private DepartmentService departmentService;
	private UniversityService universityService;
	private DiplomaService diplomaService;

	Logger log = Logger.getLogger(HandleEmployeeController.class);

	public HandleEmployeeController() {
		super();
		setSessionForm(true);
		setCommandName("employee");
		setCommandClass(Employee.class);
		setFormView(UrlConstants.HANDLE_EMPLOYEE_URL);
		setSuccessView(UrlConstants.HANDLE_EMPLOYEE_URL);
	}

	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		Employee employee = null;
		int id = ParamUtil.getInteger(request, "id", 0);
		employee = employeeService.findById(new Long(id));
		if (employee == null) {
			employee = new Employee();
		}
		return employee;
	}

	@Override
	public void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(
				dateFormat, true));
		if (request instanceof MultipartHttpServletRequest) {
			binder.registerCustomEditor(String.class,
					new StringMultipartFileEditor());
		}
	}

	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		Employee informEmployee = (Employee) command;
		String cmd = ParamUtil.getString(request, Constants.CMD, "");
		String imageurl = FileUtil.transferTo(request, "imageurl",
				Constants.UPLOADED_FILE_FOLDER);
		if (!imageurl.isEmpty()) {
			informEmployee.setImageurl(imageurl);
		} else if (Constants.EDIT.equals(cmd)) {
			long id = informEmployee.getEmployeeid();
			Employee inDBEmployee = employeeService.findById(id);
			if (inDBEmployee != null) {
				informEmployee.setImageurl(inDBEmployee.getImageurl());
			}
		}

		if (Constants.EDIT.equals(cmd)) {
			employeeService.saveOrUpdate(informEmployee);
			request.setAttribute("editOK", true);
		} else if (Constants.ADD.equals(cmd)) {
			employeeService.save(informEmployee);
			request.setAttribute("addOK", true);
		}

		return showForm(request, response, errors);
	}

	@Override
	protected ModelAndView showForm(HttpServletRequest request,
			HttpServletResponse response, BindException errors)
			throws Exception {
		if (userService.isSignedIn(request)) {
			Map<String, Object> bean = new HashMap<String, Object>();
			String loginName = userService.getCurrentLogin(request);
			User user = userService.findByLoginName(loginName);
			bean.put("user", user);
			bean.put("isSigned", true);
			bean.put("isAdmin", userService.isAdmin(loginName));
			bean.put(Constants.LOGIN_NAME, loginName);
			bean.put(Constants.USER_NAME, userService.getUsername(loginName));
			bean.put("visa", user.getEmployee().getVisa());

			bean.put("ranks", rankService.getAll());
			bean.put("departments", departmentService.getAll());
			bean.put("universities", universityService.getAll());
			bean.put("diplomas", diplomaService.getAll());

			String cmd = ParamUtil.getString(request, Constants.CMD, "");
			bean.put(Constants.CMD, cmd);

			String returnToFullPageURL = ParamUtil.getString(request,
					Constants.RETURN_TO_FULL_PAGE_URL, "");

			if (returnToFullPageURL.isEmpty()) {
				returnToFullPageURL = request.getHeader("referer");
			}
			bean.put(Constants.RETURN_TO_FULL_PAGE_URL, returnToFullPageURL);

			request.setAttribute("bean", bean);
		} else {
			String cmd = ParamUtil.getString(request, Constants.CMD, "");
			String redirectLink = "";
			if (Constants.ADD.equals(cmd)) {
				redirectLink = UrlConstants.HANDLE_EMPLOYEE_URL
						+ UrlConstants.HTM;
			} else if (Constants.EDIT.equals(cmd)) {
				int id = ParamUtil.getInteger(request, "id", 0);
				redirectLink = UrlConstants.HANDLE_EMPLOYEE_URL
						+ UrlConstants.HTM + "?id=" + id;
			}

			request.getSession().setAttribute("redirectLink", redirectLink);
			response.sendRedirect(UrlConstants.HOME_PAGE_URL + UrlConstants.HTM);
		}
		return super.showForm(request, response, errors);
	}

	public EmployeeService getEmployeeService() {
		return employeeService;
	}

	public void setEmployeeService(EmployeeService employeeService) {
		this.employeeService = employeeService;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public RankService getRankService() {
		return rankService;
	}

	public void setRankService(RankService rankService) {
		this.rankService = rankService;
	}

	public DepartmentService getDepartmentService() {
		return departmentService;
	}

	public void setDepartmentService(DepartmentService departmentService) {
		this.departmentService = departmentService;
	}

	public UniversityService getUniversityService() {
		return universityService;
	}

	public void setUniversityService(UniversityService universityService) {
		this.universityService = universityService;
	}

	public DiplomaService getDiplomaService() {
		return diplomaService;
	}

	public void setDiplomaService(DiplomaService diplomaService) {
		this.diplomaService = diplomaService;
	}

}
